﻿using System;
using System.Globalization;
using UnityEngine;
using UnityEngine.Profiling;

public class PerformanceMonitor : MonoBehaviour
{
    // 窗口参数
    private bool _showDebug = true;
    private Rect _windowRect = new Rect(10, 10, 600, 400);
    private int _windowID = 0;

    // FPS计算参数
    private float _updateInterval = 0.5f;
    private float _accumulatedTime = 0f;
    private int _frameCount = 0;
    private float _currentFPS = 0f;

    // 内存参数
    private float _totalMemory = 0f;
    private float _gcMemory = 0f;

    private float _timer;
    void Update()
    {
        // 计算FPS
        _accumulatedTime += Time.deltaTime;
        _frameCount++;

        if (_accumulatedTime >= _updateInterval)
        {
            _currentFPS = _frameCount / _accumulatedTime;
            _frameCount = 0;
            _accumulatedTime = 0f;
        }

        // 更新内存数据
        _totalMemory = (float)(GC.GetTotalMemory(false)) / 1048576f; // 转为MB
    }
    void OnGUI()
    {
        if (!_showDebug) return;

        GUI.skin.label.fontSize = 32;
        _windowRect = GUI.Window(_windowID, _windowRect, DebugWindow, "Performance Monitor");
    }

    void DebugWindow(int id)
    {
        // 绘制FPS信息
        GUI.color = _currentFPS < 55 ? Color.yellow : Color.green;
        GUI.color = _currentFPS < 15 ? Color.red : GUI.color;
        GUILayout.Label($"FPS: {_currentFPS.ToString("F1", CultureInfo.InvariantCulture)}");

        // 绘制DrawCall信息
#if UNITY_EDITOR
        int drawCalls = UnityEditor.UnityStats.drawCalls;
#else
        int drawCalls = -1; // 正式版需要其他获取方式
#endif
        GUI.color = drawCalls > 500 ? Color.red : Color.green;
        GUILayout.Label($"DrawCalls: {(drawCalls == -1 ? "N/A" : drawCalls.ToString())}");

        // 内存信息
        GUI.color = Color.cyan;
        GUILayout.Label($"Total Memory: {_totalMemory.ToString("F2")} MB");

        // 托管堆内存（需要启用Profiler）
#if DEVELOPMENT_BUILD || UNITY_EDITOR
        _gcMemory = (float)(Profiler.GetMonoUsedSizeLong() >> 10) / 1024f;
        GUILayout.Label($"GC Memory: {_gcMemory.ToString("F2")} MB");
#else
        GUILayout.Label("GC Memory: [Enable Development Build]");
#endif

        // 实例数量（需要自定义统计）
        // 请根据项目需求自行实现计数器
        GUILayout.Label($"Instance Count: {GameManager.Instance.TotalBallCount}");
        // GC触发按钮
        if (GUILayout.Button("Manual GC Collect"))
        {
            System.GC.Collect();
        }

        // 其他自定义参数区域
        GUILayout.Space(10);
        GUILayout.Label("Custom Parameters:");
        // 在此添加你的自定义参数监控

        // 窗口拖动功能
        GUI.DragWindow(new Rect(0, 0, 10000, 20));
    }

    void OnValidate()
    {
        // 限制最小窗口尺寸
        _windowRect.width = Mathf.Max(_windowRect.width, 250);
        _windowRect.height = Mathf.Max(_windowRect.height, 150);
    }
}